package cn.doitedu.dataservice.controller;

import cn.doitedu.dataservice.pojo.TagQueryParam;
import cn.doitedu.dataservice.pojo.UserTags;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
public class BasicApis {
    Table table = null;

    public BasicApis() throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","doit01:2181,doit02:2181,doit03:2181");
        Connection conn = ConnectionFactory.createConnection(conf);

        table = conn.getTable(TableName.valueOf("mall_user_profile"));
        System.out.println("hbase连接创建成功.....>>>>....");

    }

    @RequestMapping("/api/add/{p1}/{p2}")
    public int add(@PathVariable(value = "p1") int param1, @PathVariable(value = "p2") int param2){

        return param1 + param2;
    }


    @RequestMapping("/api/userprofile")
    public UserTags getUserTagsByGuid(long guid) throws IOException {

        HashMap<String, String> tags = new HashMap<>();

        Get get = new Get(Bytes.toBytes(guid));
        Result result = table.get(get);
        CellScanner cellScanner = result.cellScanner();
        while(cellScanner.advance()){
            Cell cell = cellScanner.current();
            byte[] tagNameBytes = CellUtil.cloneQualifier(cell);
            byte[] valueBytes = CellUtil.cloneValue(cell);

            String tagName = Bytes.toString(tagNameBytes);
            int value = Bytes.toInt(valueBytes);

            tags.put(tagName,value+"");
        }

        return new UserTags(guid,tags,tags.size());
    }

    // guid
    // [tag0001,tag0002,tag1002]
    @RequestMapping(method = RequestMethod.POST,value = "/api/userprofile2")
    public UserTags getUserTags(@RequestBody TagQueryParam tagQueryParam) throws IOException {

        HashMap<String, String> tags = new HashMap<>();

        Get get = new Get(Bytes.toBytes(tagQueryParam.getGuid()));
        ArrayList<String> tagNames = tagQueryParam.getTagNames();
        for (String tagName : tagNames) {
            get.addColumn("f".getBytes(),tagName.getBytes());
        }

        Result result = table.get(get);
        for (String tagName : tagNames) {
            byte[] valueBytes = result.getValue("f".getBytes(), tagName.getBytes());
            if(valueBytes != null && valueBytes.length>0){
                int value = Bytes.toInt(valueBytes);
                tags.put(tagName,value+"");
            }
        }

        return new UserTags(tagQueryParam.getGuid(),tags,tags.size());
    }



}
